<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考勤时长" prop="attendanceTime">
        <el-select v-model="queryParams.attendanceTime" placeholder="请选择考勤时长" clearable>
          <el-option
            v-for="dict in dict.type.attendance_time"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考勤类型" prop="attendanceType">
        <el-select v-model="queryParams.attendanceType" placeholder="请选择考勤类型" clearable>
          <el-option
            v-for="dict in dict.type.attendance_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
                        v-model="queryParams.createTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 摄像头弹窗 -->
    <el-dialog
      title="人脸验证"
      :visible.sync="cameraDialogVisible"
      width="500px"
      @close="closeCamera"
    >
      <video ref="videoElement" class="camera-preview" autoplay playsinline></video>
      <div slot="footer" class="dialog-footer">
        <el-button @click="capturePhoto" type="primary" :loading="captureLoading">
          {{ captureLoading ? '正在验证...' : '开始验证' }}
        </el-button>
      </div>
    </el-dialog>

    <el-table v-loading="loading" :data="attendanceRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="考勤ID" align="center" prop="attendanceId"/>
      <el-table-column label="课程名称" align="center" prop="courseName"/>
      <el-table-column label="考勤时长" align="center" prop="attendanceTime">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.attendance_time" :value="scope.row.attendanceTime"/>
        </template>
      </el-table-column>
      <el-table-column label="考勤类型" align="center" prop="attendanceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.attendance_type" :value="scope.row.attendanceType"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}点{i}分') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <span
            v-if="scope.row.signStatus === undefined || scope.row.signStatus === null || scope.row.signStatus === ''">
            <el-button
              size="mini"
              type="text"
              :icon="scope.row.attendanceType === 0 ? 'el-icon-full-screen' : 'el-icon-camera'"
              @click="scope.row.attendanceType === 0 ? scanSign() : handleOpenCamera(scope.row.courseRecordId)"
              v-hasPermi="['attendance:sign:add']"
            >签到</el-button>
          </span>
          <span v-else>
            <dict-tag :options="dict.type.sign_status" :value="scope.row.signStatus"/>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {
  listAttendanceRecord,
  getAttendanceRecord,
  delAttendanceRecord,
  addAttendanceRecord,
  updateAttendanceRecord,
  listAttendanceRecordForStudent,
  getSignStatus
} from "@/api/attendance/attendanceRecord";
import {addSign, uploadPhoto} from "@/api/attendance/sign";
import Vue from "vue";
import {mapGetters} from 'vuex'

export default {
  name: "sign",
  dicts: ['attendance_type', 'attendance_time', 'sign_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考勤记录表格数据
      attendanceRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseName: null,
        attendanceTime: null,
        attendanceType: null,
        createTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        courseId: [
          {required: true, message: "课程ID不能为空", trigger: "blur"}
        ],
        userId: [
          {required: true, message: "教师ID不能为空", trigger: "blur"}
        ],
        attendanceTime: [
          {required: true, message: "考勤时长不能为空", trigger: "change"}
        ],
        attendanceType: [
          {required: true, message: "考勤类型不能为空", trigger: "change"}
        ],
      },
      // 新增摄像头相关状态
      cameraDialogVisible: false,
      videoStream: null,
      captureLoading: false,
      courseRecordId: null,
      faceScore: null // 用于存储人脸识别的分数
    };
  },
  created() {
    this.getList();
  },
  computed: {
    ...mapGetters(['avatar']),
    hasAvatar() {
      const defaultAvatar = require('@/assets/images/profile.jpg');
      return this.avatar && this.avatar !== defaultAvatar;
    }
  },
  methods: {
    checkAvatar() {
      if (this.hasAvatar) {
        this.$modal.msgSuccess('用户有头像');
      } else {
        this.$modal.msgWarning('用户没有头像');
      }
    },
    scanSign() {
      this.$modal.msgWarning('请扫描教师端二维码签到...');
    },
    // 打开摄像头
    async handleOpenCamera(courseRecordId) {
      this.courseRecordId = courseRecordId;
      if (this.hasAvatar) { // 用户有个人头像
        if (!navigator.mediaDevices) {
          this.$modal.msgError('当前浏览器不支持摄像头访问');
          return;
        }
        try {
          this.videoStream = await navigator.mediaDevices.getUserMedia({
            video: {facingMode: "user"} // 前置摄像头
          })
          this.cameraDialogVisible = true
          this.$nextTick(() => {
            const video = this.$refs.videoElement
            video.srcObject = this.videoStream
          })
        } catch (error) {
          this.$modal.msgError('摄像头访问失败: ' + error.message)
        }
      } else {
        this.$modal.msgWarning('签到前必须在[个人中心]上传个人头像(证件照或者清晰面部照片)！');
      }

    },
    // 拍照并处理
    async capturePhoto() {
      try {
        this.captureLoading = true
        const video = this.$refs.videoElement
        const canvas = document.createElement('canvas')
        canvas.width = video.videoWidth
        canvas.height = video.videoHeight
        canvas.getContext('2d').drawImage(video, 0, 0)

        // 获取base64图片数据
        const photoData = canvas.toDataURL('image/jpeg', 0.8)

        // 将 base64 转换为 Blob 对象
        const blob = await this.dataURLToBlob(photoData);

        // 创建 FormData 对象
        const formData = new FormData();
        formData.append('signPhoto', blob, 'sign_photo.jpg');

        // 获取用户头像信息并转换为 Blob 对象
        // 处理为路径的情况，这里假设路径是相对路径，需要根据实际情况调整
        const img = new Image();
        img.src = this.avatar;
        await new Promise((resolve) => img.onload = resolve);
        const canvas2 = document.createElement('canvas');
        canvas2.width = img.width;
        canvas2.height = img.height;
        const ctx = canvas2.getContext('2d');
        ctx.drawImage(img, 0, 0);
        const avatarData = canvas2.toDataURL('image/jpeg');
        const avatarBlob = await this.dataURLToBlob(avatarData);
        formData.append('avatarPhoto', avatarBlob, 'avatar_photo.jpg');

        // 上传图片到服务器的逻辑
        const response = await uploadPhoto(formData);
        this.handleUploadResponse(response);

        this.closeCamera()
      } catch (error) {
        this.$modal.msgError('验证失败: ' + error.message)
        console.log('验证失败: ' + error.message);
      } finally {
        this.captureLoading = false
      }
    },
    handleUploadResponse(response) {
      if (response.error_msg && response.error_msg.toUpperCase() === 'SUCCESS') {
        // 人脸识别成功
        this.faceScore = response.result ? response.result.score : null;

        // 根据结果调用签到插入数据库
        if (this.faceScore >= 80) { // 阈值为80，大于等于80即人脸对比成功
          this.$modal.msgSuccess('人脸识别成功');
          this.sign(this.courseRecordId);
        } else {
          this.$modal.msgWarning('对比度：' + Math.round(this.faceScore) + ' 请重试，人脸对比失败, 请保证面部无遮挡，光照正常等...');
        }
      } else {
        // 显示警告弹窗
        this.$modal.msgError('人脸对比失败：', response.error_msg);
        console.log(response.error_msg);
      }
    },
    dataURLToBlob(dataURL) {
      return new Promise((resolve) => {
        const arr = dataURL.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        resolve(new Blob([u8arr], {type: mime}));
      });
    },
    // 关闭摄像头
    closeCamera() {
      if (this.videoStream) {
        this.videoStream.getTracks().forEach(track => track.stop())
        this.videoStream = null
      }
      this.cameraDialogVisible = false
    },

    /** 查询考勤记录列表 */
    async getList() {
      this.loading = true;
      try {
        const response = await listAttendanceRecordForStudent(this.queryParams);
        this.attendanceRecordList = response.rows;
        this.total = response.total;
        // 每行增加字段signStatus
        this.attendanceRecordList.forEach(attendance => {
          Vue.set(attendance, 'signStatus', null);
        });
        const promises = this.attendanceRecordList.map(attendance => {
          return getSignStatus(attendance.courseRecordId).then(res => {
            attendance.signStatus = res.data;
            return attendance;
          })
        });
        // 等待所有查询完成
        Promise.all(promises).then(() => {
          this.loading = false;
        });
      } catch (error) {
        console.error('获取考勤记录列表失败:', error);
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        attendanceId: null,
        courseRecordId: null,
        courseId: null,
        courseName: null,
        userId: null,
        deptId: null,
        attendanceTime: null,
        attendanceType: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.attendanceId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考勤记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const attendanceId = row.attendanceId || this.ids
      getAttendanceRecord(attendanceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考勤记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.attendanceId != null) {
            updateAttendanceRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttendanceRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const attendanceIds = row.attendanceId || this.ids;
      this.$modal.confirm('是否确认删除考勤记录编号为"' + attendanceIds + '"的数据项？').then(function () {
        return delAttendanceRecord(attendanceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('attendance/attendanceRecord/export', {
        ...this.queryParams
      }, `attendanceRecord_${new Date().getTime()}.xlsx`)
    },
    /** 签到 */
    sign(courseRecordId) {
      const signData = {
        courseRecordId: courseRecordId
      };
      // 调用 addSign 函数发起签到请求
      addSign(signData)
        .then(response => {
          // 请求成功的处理逻辑
          this.$modal.msgSuccess("签到成功");
          this.getList();
        })
        .catch(error => {
          // 请求失败的处理逻辑
          this.$modal.msgError(error);
        });
    }
  },
  // 组件销毁前释放摄像头资源
  beforeDestroy() {
    this.closeCamera()
  }
};
</script>

<style scoped>
.camera-preview {
  width: 100%;
  border-radius: 4px;
  background: #000;
}
</style>
